<template>
  <view class="pageLayout">
    <u--form
      labelPosition="top"
      :model="form"
      :rules="rules"
      ref="MyForm"
      labelWidth="500rpx"
      :labelStyle="labelStyle"
    >
      <view class="base_info">
        <!-- <u-form-item label="所属部门" borderBottom>
          <u--input
            placeholder="请输入"
            :fontSize="fontSize"
            v-model="userInfo.teamName"
            border="none"
            :disabled="true"
            disabledColor="#ffffff"
          ></u--input>
        </u-form-item> -->
        <u-form-item required label="项目名称" prop="approveTopic" borderBottom>
          <u--textarea
            placeholder="请输入项目名称"
            :fontSize="fontSize"
            v-model="form.approveTopic"
            autoHeight
            border="none"
            :disabled="disable"
            :maxlength="14"
            count
          ></u--textarea>
        </u-form-item>
        <u-form-item
          required
          label="项目说明"
          prop="approveContent"
          borderBottom
        >
          <u--textarea
            placeholder="请输入"
            :fontSize="fontSize"
            v-model="form.approveContent"
            autoHeight
            border="none"
            :disabled="disable"
            :maxlength="60"
            count
          ></u--textarea>
        </u-form-item>
        <u-form-item
          required
          label="计划完成时间"
          prop="expectedTime"
          borderBottom
          @click="showTimePickerFn('expectedTime')"
        >
          <u--input
            v-model="form.expectedTime"
            border="none"
            disabled
            disabledColor="#ffffff"
            placeholder="请选择"
            :inputAlign="inputAlign"
            :fontSize="fontSize"
            suffixIcon="arrow-right"
            :suffixIconStyle="{ color: '#c0c4cc' }"
          ></u--input>
        </u-form-item>
        <u-form-item required label="是否涉及费用" prop="hasCost">
          <u-radio-group
            v-model="form.hasCost"
            placement="row"
            activeColor="#a22c26"
          >
            <u-radio
              :customStyle="{
                marginRight: '80px',
                marginTop: '20px',
                marginBottom: '10px',
                fontWeight: 'bold',
              }"
              label="是"
              :name="true"
            ></u-radio>
            <u-radio
              :customStyle="{
                marginTop: '20px',
                marginBottom: '10px',
                fontWeight: 'bold',
              }"
              label="否"
              :name="false"
            >
            </u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item borderBottom prop="costAmount" v-if="form.hasCost">
          <u-input
            type="number"
            placeholder="请输入金额"
            :fontSize="fontSize"
            v-model="form.costAmount"
            border="none"
            disabledColor="#ffffff"
          >
            <template v-slot:suffix>
              <text>元</text>
            </template>
          </u-input>
        </u-form-item>
        <u-form-item
          label="添加参与人"
          prop="attendUserID"
          borderBottom
          @click="showParticipantPickerFn"
        >
          <multiPicker
            :value="participantInfo"
            :list="userList"
            :show.sync="showParticipantPicker"
            title="请选择"
            :show-search="true"
            key-name="label"
            id-name="value"
            :inputAlign="'left'"
            @confirm="handlePhoneConfirm"
            :multiselect="false"
          />
        </u-form-item>
        <u-form-item>
          <view class="labelStyle" style="font-size: 24rpx">计划图片</view>
          <custom-upload
            v-model="fileList"
            :max-count="1"
            @change="handleFileChange"
            :disabled="disable"
          />
        </u-form-item>
      </view>
    </u--form>
    <!-- <view class="info_box" v-if="detail">
      <view class="server_info">
        <u-row>
          <u-col span="4">
            <view class="">
              <view class="info_title">
                <u-icon name="account-fill" color="#8d8d92" size="14"></u-icon>
                <view> 申请人 </view>
              </view>
              <view class="info_name">{{
                detail.startName ? detail.startName : "——"
              }}</view>
            </view>
          </u-col>
          <u-col span="8">
            <view class="">
              <view class="">
                <view class="info_title">申请时间</view>
                <view class="info_name">{{
                  detail.startTime ? detail.startTime : "——"
                }}</view>
              </view>
            </view>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="4">
            <view class="">
              <view class="info_title">审批流程</view>
              <view class="info_name">{{
                detail.approveProcessStateDesc
                  ? detail.approveProcessStateDesc
                  : "——"
              }}</view>
            </view>
          </u-col>
        </u-row>
        <u-row v-if="detail.oneApproveContent">
          <u-col span="12">
            <view class="">
              <view class="info_title">程总意见</view>
              <view class="info_name">{{
                detail.oneApproveContent ? detail.oneApproveContent : "——"
              }}</view>
            </view>
          </u-col>
        </u-row>
        <u-row v-if="detail.twoApproveContent">
          <u-col span="12">
            <view class="">
              <view class="info_title">孙总意见</view>
              <view class="info_name">{{
                detail.twoApproveContent ? detail.twoApproveContent : "——"
              }}</view>
            </view>
          </u-col>
        </u-row>
      </view>
    </view> -->
    <view
      class="bot_btn"
    >
      <view class="btn_width" ref="btnBox">
        <u-button
          v-if="!id"
          class="btn"
          :loading="loading"
          @click="submitForm"
          :color="isSubmit ? '#f6f6f6' : '#a22d27'"
          :disabled="isSubmit"
          :customStyle="`color:${isSubmit ? '#C8C9CC' : '#ffffff'};`"
          >提交申请</u-button
        >
        <!-- <u-button
          v-if="
            (detail.approveProcessState == 'Commit' &&
              detail.adminType == 'None') ||
            (detail.adminType == 'ChengZong' &&
              detail.approveProcessState == 'OnePass' &&
              detail.startID == '1369897532213166080')
          "
          class="btn"
          :loading="loading"
          @click="cancelApprove"
          size="small"
          shape="circle"
          color="#a22d27"
          customStyle="margin-left: 20rpx;padding:8rpx 22rpx;border:1rpx solid #A22C26;color: #ffffff;font-weight:700;"
          >取消申请</u-button
        >
        <u-button
          v-if="detail.approveProcessState == 'Cancel'"
          class="btn"
          :loading="loading"
          @click="reApprove"
          size="small"
          shape="circle"
          color="#a22d27"
          customStyle="margin-left: 20rpx;padding:8rpx 22rpx;border:1rpx solid #A22C26;color: #ffffff;font-weight:700;"
          >重新发起</u-button
        >
        <u-button
          v-if="
            (detail.adminType == 'ChengZong' &&
              chengzongList.includes(detail.approveProcessState)) ||
            (detail.adminType == 'TopAdmin' &&
              sonzongList.includes(detail.approveProcessState))
          "
          class="btn"
          :loading="loading"
          @click="rejectApprove"
          size="small"
          shape="circle"
          color="#a22d27"
          :plain="true"
          customStyle="margin-left: 20rpx;padding:8rpx 22rpx;border:1rpx solid #A22C26;font-weight:700;"
          >驳回</u-button
        >
        <u-button
          v-if="
            (detail.adminType == 'ChengZong' &&
              chengzongList.includes(detail.approveProcessState)) ||
            (detail.adminType == 'TopAdmin' &&
              sonzongList.includes(detail.approveProcessState))
          "
          class="btn"
          :loading="loading"
          @click="agreeApprove"
          size="small"
          shape="circle"
          color="#a22d27"
          customStyle="margin-left: 20rpx;padding:8rpx 22rpx;border:1rpx solid #A22C26;color: #ffffff;font-weight:700;"
          >同意</u-button
        > -->
      </view>
    </view>
    <u-popup :show="showReject" @close="closeForm" mode="bottom" closeable>
      <view class="pop_box">
        <u--form
          labelPosition="left"
          :model="agreeForm"
          :rules="agreeRules"
          ref="AgreeForm"
          :labelStyle="labelStyle"
        >
          <view class="base_info" style="height: 500rpx">
            <u-form-item labelPosition="top" prop="content" borderBottom>
              <view class="labelStyle" style="font-size: 24rpx">审批意见</view>
              <u--textarea
                v-model="agreeForm.content"
                border="none"
                height="150"
                placeholder="请输入"
              ></u--textarea>
            </u-form-item>
            <u-button
              :loading="loading"
              @click="submitAgree"
              size="small"
              shape="circle"
              color="#a22d27"
              customStyle="padding:8rpx 22rpx;border:1rpx solid #A22C26;color: #ffffff;font-weight:700;margin-top:20rpx;"
              >{{ type == 1 ? "驳回" : "同意" }}</u-button
            >
          </view>
        </u--form>
      </view>
    </u-popup>

    <u-datetime-picker
      :show="showDatePicker"
      v-model="Date"
      mode="date"
      @confirm="changeDatePicker"
      @cancel="closeDatePicker"
      :minDate="todayTimestamp"
      confirmColor="#a22d27"
      :immediateChange="true"
    ></u-datetime-picker>
    <mytoast ref="toastRef" />
  </view>
</template>
  <script>
import store from "../../store/index";
import myPicker from "@/components/myPicker";
import customUpload from "@/components/customUpload.vue";
import mytoast from "@/components/mytoast.vue";
import multiPicker from "@/components/multiPicker";
import {
  commitApprove,
  queryApproveDetailByID,
  cancelApprove,
  cancelStart,
  reject,
  approve,
  queryOrganizeFrameworkPeopleSelect,
} from "../api/approval/index";
export default {
  components: {
    myPicker,
    customUpload,
    mytoast,
    multiPicker,
  },

  data() {
    return {
      // imgUrl: "https://www.yinyaoit.com",
      id: "",
      Date: null,
      timeKey: "", //日期选择器绑定的key
      todayTimestamp: "",
      showLinkPicker: false, //链接状态
      showServiceTypePicker: false, //服务类型
      showLevelPicker: false, //SA分级
      showNotPicker: false, //签约结果
      showPicker: false, //
      loading: false,
      showReject: false,
      showDatePicker: false, //日期选择器
      showParticipantPicker: false, //参与人选择器
      fileList: [],
      labelStyle: {
        "font-size": "30rpx",
        "font-weight": "700",
      },
      fontSize: "28rpx",
      inputAlign: "left",
      form: {
        approveTopic: "",
        approveContent: "",
        approveImage: "",
        expectedTime: "",
        hasCost: null,
        costAmount: "",
      },
      participantInfo: null,
      chengzongList: ["Commit"],
      sonzongList: ["Commit", "OneReject", "OnePass"],
      detail: null,
      selectedItems: [],
      rules: {
        approveTopic: [
          {
            type: "string",
            required: true,
            message: "请输入审批主题",
            trigger: ["blur"],
          },
        ],
        approveContent: [
          {
            type: "string",
            required: true,
            message: "请输入项目说明",
            trigger: ["blur"],
          },
        ],
        expectedTime: [
          {
            type: "string",
            required: true,
            message: "请选择完成时间",
            trigger: ["change"],
          },
        ],
        hasCost: [
          {
            type: "boolean",
            required: true,
            message: "请选择",
            trigger: ["change"],
          },
        ],
        costAmount: [
          {
            type: "number",
            required: true,
            message: "请选择",
            trigger: ["blur"],
          },
        ],
      },
      agreeRules: {
        content: [
          {
            type: "string",
            required: false,
            message: "审批意见",
            trigger: ["blur"],
          },
        ],
      },
      type: null, //1驳回 2同意
      agreeForm: {
        content: "",
        approveID: "",
      },
      userList: [],
    };
  },
  computed: {
    /**
     * 提交按钮禁用
     */
    isSubmit() {
      if (this.form.approveTopic == "" || this.form.approveContent == "") {
        return true;
      } else {
        return false;
      }
    },
    hasLogin() {
      return this.$store.state.token && this.$store.state.token.length > 0;
    },
    // hasBtn(){
    //   this.$refs.btnBox
    // },
    disable() {
      if (this.detail && this.detail.approveProcessState == "Cancel") {
        return false;
      } else if (!this.id) {
        return false;
      } else if (!this.detail) {
        return false;
      } else if (
        this.detail.adminType == "None" &&
        this.detail.approveProcessState == "Commit"
      ) {
        return true;
      } else if (
        this.detail.adminType == "ChengZong" &&
        this.detail.approveProcessState == "OnePass" &&
        this.detail.startID == "1369897532213166080"
      ) {
        return false;
      } else {
        return true;
      }
    },
  },
  methods: {
    showParticipantPickerFn() {
      this.showParticipantPicker = true;
    },
    /**
     * 获取手机区号
     */
    handlePhoneConfirm(val) {
      console.log(val, "handlePhoneConfirm");
      this.participantInfo = val;
      this.form.attendUserID = val.value; //参与人id
    },
    /**
     * 获取组织架构树
     */
    getUserList() {
      let data = {
        searchValue: "",
      };
      queryOrganizeFrameworkPeopleSelect(data)
        .then((res) => {
          console.log(res, "getUserList");
          this.userList = res.data.map((item) => {
            return {
              ...item,
              ...item.extensios,
              label: item.extensios.frameworkName + " - " + item.showOption,
            };
          });
          console.log(this.userList, "this.userList");
        })
        .catch((e) => {
          this.loading = false;
          this.$refs.toastRef.showToast({
            msg: e.data.detail,
            duration: 3000,
            position: "center",
          });
        });
    },
    /**
     * 关闭时间选择器
     */
    closeDatePicker() {
      this.showDatePicker = false;
    },
    /**
     * 打开时间选择器
     * @param key 键值
     */
    showTimePickerFn(key) {
      this.timeKey = key;
      this.showDatePicker = true;
    },
    /**
     * 获取时间选择范围
     */
    getDateSele() {
      const { todayZero, afterTomorrowZero } = this.getZeroTimestamps();
      this.todayTimestamp = todayZero;
      // this.MaxTimestamp = afterTomorrowZero;
      this.Date = todayZero;
    },
    /**
     * 获取当天和后天零点时间戳
     * @param {boolean} isUTC 是否使用UTC时间
     * @returns { todayZero: number, afterTomorrowZero: number }
     */
    getZeroTimestamps(isUTC = false) {
      const getZeroDate = () => {
        const date = new Date();

        date.setHours(0, 0, 0, 0);
        return date;
      };

      // 当天零点
      const todayZero = getZeroDate().getTime();

      // 明天零点
      const afterTomorrowDate = getZeroDate();
      afterTomorrowDate.setDate(afterTomorrowDate.getDate() + 1);
      const afterTomorrowZero = afterTomorrowDate.getTime();

      return { todayZero, afterTomorrowZero };
    },
    /**
     * 日期选择
     */
    changeDatePicker(val) {
      let date;
      date = this.formatTimestamp(val.value, "onlyDate");
      this.form[this.timeKey] = date;
      this.showDatePicker = false;
      console.log(this.form);
    },
    /**
     * 关闭弹窗
     *
     */
    closeForm() {
      this.agreeForm = {
        content: "",
        approveID: "",
      };
      this.showReject = false;
      this.$refs.AgreeForm.resetFields();
    },
    /**
     * 审核
     */
    async submitAgree() {
      // let action = await this.$refs.AgreeForm.validate();
      let data = {
        ...this.agreeForm,
      };
      console.log(data, this.type);
      // setTimeout(() => {
      //   uni.navigateBack({ delta: 1 });
      // }, 1000);

      // return;
      this.loading = true;
      if (this.type == 1) {
        reject(data)
          .then((res) => {
            this.loading = false;
            this.$refs.toastRef.showToast({
              msg: "操作成功",
              duration: 3000,
              position: "center",
            });
            this.closeForm();
            this.getInfo();
            setTimeout(() => {
              uni.navigateBack({ delta: 1 });
            }, 1000);
          })
          .catch((e) => {
            this.loading = false;
            this.$refs.toastRef.showToast({
              msg: e.data.detail,
              duration: 3000,
              position: "center",
            });
          });
      } else if (this.type == 2) {
        approve(data)
          .then((res) => {
            this.loading = false;
            this.$refs.toastRef.showToast({
              msg: "操作成功",
              duration: 3000,
              position: "center",
            });
            this.closeForm();
            this.getInfo();
            setTimeout(() => {
              uni.navigateBack({ delta: 1 });
            }, 1000);
          })
          .catch((e) => {
            this.loading = false;
            this.$refs.toastRef.showToast({
              msg: e.data.detail,
              duration: 3000,
              position: "center",
            });
          });
      }
      console.log(this.form, "this.form");
    },
    /**
     * 拒绝
     */
    rejectApprove() {
      this.agreeForm.approveID = this.id;
      this.type = 1;
      this.showReject = true;
    },
    /**
     * 同意
     */
    agreeApprove() {
      this.agreeForm.approveID = this.id;
      this.type = 2;
      this.showReject = true;
    },
    /**
     * 图片上传反馈
     * @param files 当前文件列表
     */
    handleFileChange(files) {
      console.log("当前文件列表:", files);
    },
    /**
     * 链接状态
     */
    changeLink(val) {
      console.log(val, "changeLink");
    },
    /**
     * 表单提交
     */
    async submitForm() {
      // if (this.fileList.length == 0) {
      //   uni.showToast({
      //     title: "请上传审批图片",
      //     icon: "none",
      //     duration: 1500,
      //   });
      //   return;
      // }
      let action = await this.$refs.MyForm.validate();
      if (action) {
        // return;
        let imgArr = [];
        if (this.fileList.length >= 0) {
          imgArr = this.fileList.map((item) => {
            return item.path;
          });
        }

        let data = {
          ...this.form,
          approveImage: imgArr.length > 0 ? imgArr.join(",") : "",
        };
        console.log(data, "data");
        // return
        this.loading = true;
        if (!this.id) {
          commitApprove(data)
            .then((res) => {
              this.loading = false;
              this.$refs.toastRef.showToast({
                msg: "申请成功",
                duration: 3000,
                position: "center",
              });
              setTimeout(() => {
                uni.navigateBack();
              }, 1000);
            })
            .catch((e) => {
              this.loading = false;
              this.$refs.toastRef.showToast({
                msg: e.data.detail,
                duration: 3000,
                position: "center",
              });
            });
        } else {
          data.approveID = this.id;
          cancelStart(data)
            .then((res) => {
              this.loading = false;
              this.$refs.toastRef.showToast({
                msg: "重新发起成功",
                duration: 3000,
                position: "center",
              });
              setTimeout(() => {
                uni.navigateBack();
              }, 1000);
            })
            .catch((e) => {
              this.loading = false;
              this.$refs.toastRef.showToast({
                msg: e.data.detail,
                duration: 3000,
                position: "center",
              });
            });
        }

        console.log(this.form, "this.form");
      } else {
        uni.showToast({ title: "请完善表单", icon: "none" });
        return false;
      }
    },
    /**
     * 取消审批
     */
    cancelApprove() {
      let that = this;
      uni.showModal({
        title: "温馨提示",
        content: "你确定要取消审批吗？",
        showCancel: true,
        confirmText: "确定",
        success: (res) => {
          if (res.confirm) {
            cancelApprove({ approveID: that.id })
              .then((res) => {
                that.$refs.toastRef.showToast({
                  msg: "取消成功",
                  duration: 3000,
                  position: "center",
                });
                setTimeout(() => {
                  uni.navigateBack();
                }, 1000);
              })
              .catch((e) => {
                console.log(e);

                this.$refs.toastRef.showToast({
                  msg: e.data.detail,
                  duration: 3000,
                  position: "center",
                });
              });
          } else if (res.cancel) {
            return;
          }
        },
      });
    },
    /**
     * 重新发起审批
     */
    reApprove() {
      let that = this;
      uni.showModal({
        title: "温馨提示",
        content: "你确定要重新发起审批吗？",
        showCancel: true,
        confirmText: "确定",
        success: (res) => {
          if (res.confirm) {
            that.submitForm();
          } else if (res.cancel) {
            return;
          }
        },
      });
    },
    /**
     * 获取详情
     */
    getInfo() {
      queryApproveDetailByID({ approveID: this.id }).then((res) => {
        console.log(res);
        this.form.approveTopic = res.data.approveTopic;
        this.form.approveContent = res.data.approveContent;
        this.form.expectedTime = res.data.expectedTime;
        this.form.hasCost = res.data.hasCost;
        this.form.blur = res.data.blur;
        this.form.approveImage = res.data.approveImage;
        this.form.approveID = res.data.approveID;
        this.detail = res.data;
        this.fileList = res.data.approveImage.split(",").map((item) => {
          return {
            path: item,
            url: this.imgUrl + "/" + item,
            status: "success",
          };
        });
      });
    },
  },
  onLoad(options) {
    this.id = options.id;
    if (this.id) {
      this.getInfo();
    }
  },
  onShow() {
    this.getDateSele();
    this.getUserList();
  },
  onReady() {
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    this.$refs.MyForm.setRules(this.rules);
    this.$refs.AgreeForm.setRules(this.agreeRules);
  },
  /**
   * 上拉加载更多
   */
  onReachBottom() {},
};
</script>
  <style>
page {
  background-color: #ffffff;
}
</style>
  
  <style lang="scss" scoped>
.pageLayout {
  padding: 24rpx;
  padding-bottom: 80rpx;
}
.base_info {
  background-color: #ffffff;
  padding: 24rpx;
  box-sizing: border-box;
  border-radius: 8rpx;
  margin-bottom: 24rpx;
}
.labelStyle {
  margin-bottom: 24rpx;
  font-weight: 700;
  font-size: 26rpx;
}
.submit-container {
  margin-top: 40rpx;
  padding: 20rpx;
  background-color: #f5f7fb;
}
// .btn_width {
//   width: 60%;
//   margin: 60rpx auto;
// }
.bot_btn {
  // background-color: #d52227;
  // border-top: 1rpx solid #801c1b26;
  // position: fixed;
  // bottom: 0;
  // left: 0;
  width: 100%;
  margin-top: 40rpx;
  // box-shadow: #a5a5a5 0px 0px 6px;
  padding: 20rpx;
  padding-bottom: 50rpx;
  // background-color: white;
  box-sizing: border-box;
  .btn_width {
    margin: 0 auto;
    display: flex;
    justify-content: space-between;
  }
}
.info_box {
  width: 670rpx;
  background: #ffffff;
  border-radius: 8rpx;
  margin-top: 24rpx;
  padding: 24rpx 40rpx;
  box-sizing: border-box;
  position: relative;
  .editIcon {
    position: absolute;
    top: 24rpx;
    right: 24rpx;
    padding: 10rpx;
    background: #e7f8fc;
    border-radius: 14rpx;
    display: flex;
    align-items: center;
    view {
      font-size: 20rpx;
      margin-left: 3rpx;
      line-height: 15rpx;
    }
  }
  .reloadIcon {
    background: #fbe6e8;
  }
  .info_title {
    font-size: 20rpx;
    color: #1c1b2680;
    display: flex;
    align-items: center;
    view {
      margin-left: 10rpx;
    }
  }
  .info_name {
    font-size: 24rpx;
    color: #1c1b26;
    margin-top: 18rpx;
    margin-bottom: 32rpx;
    font-weight: 700;
  }
}
.pop_box {
  height: 80vh;
}
::v-deep .u-textarea__count {
  color: #c8c9cc !important;
}
</style>
  